﻿/* 2013/6/10 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Cosmos.IO.FileSystemPath.Searcher
{
    /// <summary>
    /// Generates paths by specifying search condition.
    /// Search file by checking extension of files.
    /// </summary>
    public class ExtensionFilePathSearcher : FileSystemInfoPathSearcher
    {
        /// <summary>
        /// The separators of extensions in search pattern.
        /// </summary>
        protected string[] separators = new string[] { " " };

        protected string[] extensions = null;

        protected override void Prepare(string searchPattern)
        {
            extensions = searchPattern.Split(separators
                , StringSplitOptions.RemoveEmptyEntries);

            // Makes sure every extension is lower and start with dot.
            for (int i = 0; i < extensions.Length; i++)
            {
                extensions[i] = extensions[i].ToLower();
                if (!extensions[i].StartsWith("."))
                {
                    extensions[i] = String.Concat(".", extensions[i]);
                }
            }
        }

        protected override bool Match(FileSystemInfo info)
        {
            string extension = info.Extension;
            if (extension != null)
            {
                if (extensions == null || extensions.Length == 0)
                {
                    return true;
                }

                foreach (string anExtension in extensions)
                {
                    if (extension.ToLower().Equals(anExtension))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Gets or sets the separators of extensions in search pattern.
        /// </summary>
        public string[] Separators
        {
            get { return separators; }
            set { separators = value; }
        }
    }
}
